/**
 * 
 */
package com.eshopper.user.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import com.eshopper.user.model.User;
import com.eshopper.user.repository.jpa.UserRepository;
import com.eshopper.user.security.SecurityUser;

/**
 * @author Arun Kumar, Nov 28, 2014
 *
 */
@Service
public class UserServiceUtil {

	@Autowired
	private static UserRepository repository;

	public static User findUserByEmail(String emailAddress) {
		return repository.findUserByEmail(emailAddress);
	}
	
	public static String getUserDetails() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			String email = ((UserDetails) principal).getUsername();

			return email;
		}
		return null;
	}
	
	public static SecurityUser getCurrentUser() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			String email = ((UserDetails) principal).getUsername();
			
			System.out.println(" SecurityUser :: email = " + email);
			
			User loginUser = repository.findUserByEmail(email);
			return new SecurityUser(loginUser);
		}
		return null;
	}

}
